from django.shortcuts import render,redirect

# Create your views here.
from .models import StuInfo

def table(request):
    # post请求
    if request.method == "POST":
        # 1.获取页面的值
        name = request.POST['name']
        score = request.POST['score']
        classroom = request.POST['classroom']
        skills = request.POST.getlist('skills')
        desc = request.POST['desc']
        # 2.数据库数据写入及修改
        # 查询姓名的数据行是否存在，存在旧修改，不存在就写入
        data = StuInfo.objects.filter(username=name)
        if data.exists():
            data.update(
                score=score, classroom=classroom, skills=skills, desc=desc
            )
        else:
            stu = StuInfo.objects.create(
                username=name, score=score, classroom=classroom, skills=skills,
                desc=desc
            )
            print('stu:', stu)
    # 显示所有的数据
    content = list(StuInfo.objects.all())
    print('content:', content)
    return render(request, 'table.html', {'content': content})



# 添加
def add(request):
    return render(request, 'add.html')


# 查询
def search(request):
    # get请求
    if request.method == "GET":
        return render(request, 'search.html')
    # post请求
    elif request.method == "POST":
        # 获取查询的数据条件
        name = request.POST['name']
        score = request.POST['score']
        classroom = request.POST['classroom']
        # if判断score是否为空
        if score:
            content = StuInfo.objects.filter(
                username__contains=name, score=int(score),
                classroom__contains=classroom
            )
        else:
            content = StuInfo.objects.filter(
                username__contains=name, classroom__contains=classroom
            )
    return render(request, 'search.html', locals())



# 修改
def edit(request, name):
    data = list(StuInfo.objects.filter(username=name))
    print('edit:', data)
    return render(request, 'edit.html', locals())


# 删除
def delete(request, name):
    # 使用等值查询 __exact
    data = StuInfo.objects.filter(username__exact=name)
    if data:
        data.delete()
    return redirect('/table')